package jh.com.jhappbf.contract;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.weight.query.QueryWeightDetail;

public class CollectWeigh extends AbActivity {
	private View mContentView;
	private View mErrorView;
	private Context mAppContext;
	private LinearLayout mHeaderLayout;
	private List<JSONObject> mData;
	private Button mTitleRightBtn;
	private List<String> mHeaderTitle;
	private Drawable mLeftDrawable;
	private int mColumnWidth;
	private AbLoadDialogFragment mDialogFragment = null;
	private CollectBaseAdapter mAdapter;
	private String mPlanId ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContentView = getLayoutInflater().inflate(
				R.layout.collect_input_list_activity, null);
		mErrorView = getLayoutInflater().inflate(R.layout.net_error_activity,
				null);
		setAbContentView(mContentView);
		Intent i = getIntent();
		mPlanId = i.getStringExtra("planId");

		AbTitleBar mAbTitleBar = this.getTitleBar();
		mAbTitleBar.setTitleText("计划明细");

		mAbTitleBar.setLogo(R.drawable.button_selector_back);
		mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this,R.color.orange));
		mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
		mAbTitleBar.setLogoLine(R.mipmap.line);
		mAbTitleBar.setLogoOnClickListener(v -> CollectWeigh.this.finish());
		View rightViewMore = mInflater.inflate(R.layout.title_right_app_btn_view, null);
//		mAbTitleBar.addRightView(rightViewMore);
		mTitleRightBtn = rightViewMore.findViewById(R.id.title_right_btn);
		initView();
	}

	// /初始化
	private void initView() {
		mAppContext = getApplicationContext();
		mHeaderLayout = mContentView.findViewById(R.id.collect_input_weight_title);
		ListView mListView = mContentView.findViewById(R.id.collect_input_weight_listView);
		mAdapter =new CollectBaseAdapter();
		mData = new ArrayList<>();
		mListView.setAdapter(mAdapter);
		Button mTryAgain = mErrorView.findViewById(R.id.network_error_btn);
		mHeaderTitle = new ArrayList<>();
		mLeftDrawable = ContextCompat.getDrawable(this,R.mipmap.table_line);
		mLeftDrawable.setBounds(0, 0, mLeftDrawable.getMinimumWidth(),
				mLeftDrawable.getMinimumHeight());
		mColumnWidth = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 55, getResources().getDisplayMetrics());
		mTryAgain.setOnClickListener(v -> {
			setAbContentView(mContentView);
			refresh();
		});

		mTitleRightBtn.setOnClickListener(v -> {
		});

//		mListView.setOnItemLongClickListener((parent, view, position, id) -> {
//			Intent i = new Intent(CollectWeigh.this, QueryWeightDetail.class);
//			JSONObject obj = mData.get(position);
//			String weightId = obj.optString("编号");
//			i.putExtra("flag", weightId);
//			startActivity(i);
//			return true;
//		});

		refresh();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	// /刷新
	private void refresh() {
		mDialogFragment = AbDialogUtil.showLoadDialog(CollectWeigh.this,
				R.mipmap.ic_load, "查询中,请稍等...");
		mDialogFragment.setCancelable(false);
		mDialogFragment.setAbDialogOnLoadListener(() -> getData());
	}

	// /获取数据
	private void getData() {
		String methodName = "getWeightCollectByPlanId";
		ArrayList<String> param = new ArrayList<>();
		ArrayList<String> value = new ArrayList<>();
		param.add("planId");
		value.add(mPlanId);
		Listener<String> listener = response -> {

			AbDialogUtil.removeDialog(CollectWeigh.this);
			if (mDialogFragment != null) {
				mDialogFragment.dismiss();
			}

			List<JSONObject> newListData = JsonHelper
					.getJsonObjects(response);
			if (newListData != null) {
				mHeaderTitle = new ArrayList<>();
				if(newListData.size() > 0)
				{
					String[] head = newListData.get(0).optString("alias").split(",");
					mHeaderTitle = Arrays.asList(head);
					makeHead();
				}
				mData.clear();
				mData.addAll(newListData);
				mAdapter.notifyDataSetChanged();
			}
		};

		ErrorListener errorListener = error -> {
			AbDialogUtil.removeDialog(CollectWeigh.this);
			if (mDialogFragment != null) {
				mDialogFragment.dismiss();
			}
			setAbContentView(mErrorView);
			mData.clear();
			mAdapter.notifyDataSetChanged();
		};

		VolleyCallWebService webService = new VolleyCallWebService(methodName,
				param, value, listener, errorListener, Priority.NORMAL);
		VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
	}

	// 生成表头
	private void makeHead() {
		mHeaderLayout.removeAllViews();
		for (int index = 0; index < mHeaderTitle.size(); index++) {
			TextView txt = new TextView(CollectWeigh.this);
			switch (mHeaderTitle.get(index)) {
				case "发货":
				case "收货":
					if ("发货".equals(mHeaderTitle.get(index))) {
						continue;
					}
					txt.setWidth(mColumnWidth * 3);
					break;
				case "结算重量":
				case "车号":
				case "货名":
					txt.setWidth((int) (mColumnWidth * 1.5));
					break;
				case "编号":
					txt.setWidth((int) (mColumnWidth * 2.5));
					break;
				default:
					txt.setWidth(mColumnWidth);
					break;
			}

			txt.setTextColor(Color.BLACK);
			txt.setGravity(Gravity.CENTER);
			txt.setCompoundDrawables(mLeftDrawable, null, null, null);
			txt.setPadding(1, 0, 1, 0);
			txt.setId(index);
			txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
			mHeaderLayout.addView(txt);
			txt.setText(mHeaderTitle.get(index));

		}
	}

	class CollectBaseAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Object getItem(int position) {
			return mData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressLint("NewApi")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TableLayout tableLayout;
			if (convertView == null) {
				tableLayout = new TableLayout(CollectWeigh.this);
				TableRow tableRow = new TableRow(CollectWeigh.this);
				Drawable mItemSelect = ContextCompat.getDrawable(CollectWeigh.this,R.drawable.list_item_bg);
				tableRow.setBackground(mItemSelect);
				tableRow.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
				for (int index = 0; index < mHeaderTitle.size(); index++) {
					TextView txt = new TextView(CollectWeigh.this);
					switch (mHeaderTitle.get(index)) {
						case "发货":
						case "收货":
							if ("发货".equals(mHeaderTitle.get(index))) {
								continue;
							}
							txt.setWidth(mColumnWidth * 3);
							break;
						case "结算重量":
						case "车号":
						case "货名":
							txt.setWidth((int) (mColumnWidth * 1.5));
							break;
						case "编号":
							txt.setWidth((int) (mColumnWidth * 2.5));
							break;
						default:
							txt.setWidth(mColumnWidth);
							break;
					}

					txt.setTextColor(Color.BLACK);
					txt.setGravity(Gravity.CENTER);
					txt.setCompoundDrawables(mLeftDrawable, null, null, null);
					txt.setPadding(1, 0, 1, 0);
					txt.setId(index);
					txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
					tableRow.addView(txt);

				}
				tableLayout.addView(tableRow);
				convertView = tableLayout;
				convertView.setTag(tableLayout);
			} else {
				tableLayout = (TableLayout) convertView.getTag();
			}

			JSONObject data = mData.get(position);
			String content;
			for (int index = 0; index < mHeaderTitle.size(); index++) {
				TextView txt = tableLayout.findViewById(index);
				if (txt == null) {
					continue;
				}
				content = data.optString(mHeaderTitle.get(index));
				if("null".equals(content)) {
					content = "";
				}
				switch (mHeaderTitle.get(index)) {
					case "原计划量":
					case "原剩余量":
					case "现计划量":
					case "现剩余量":
						if (!TextUtils.isEmpty(content)){
							txt.setText(new DecimalFormat("0.00").format(Double.parseDouble(content)));
						}else {
							txt.setText("0");
						}
						break;
					default:
						txt.setText(content);
						break;
				}

			}
			return convertView;
		}
	}
}
